package com.wgts.wgts.control.oss;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

/*
 *
 *
 *   data:2018/10/1014:46
 *
 */
public class OssService {

    private OSS oss;
    private static final String accessKeyId = "LTAIbsyxtT6VUYr3";

    private static final String accessKeySecret = "yCHqE7DOWltNIxSWDBrH9X6cZdGSBN";
    private static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private Context context;

    private static final String bucketName = "wgts-user";

    private static OssService _instance = null;

    private OssService(Context context) {
        this.context = context;
        initOSSClient();
    }

    public static OssService getInstance(Context context){
        if(_instance == null){
            _instance = new OssService(context);
        }
        return _instance;
    }




    private void initOSSClient() {
        //OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>");
        //这个初始化安全性没有Sts安全，如需要很高安全性建议用OSSStsTokenCredentialProvider创建（上一行创建方式）多出的参数SecurityToken为临时授权参数
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        // oss为全局变量，endpoint是一个OSS区域地址
        oss = new OSSClient(context, endpoint, credentialProvider, conf);

    }


    /**
     *
     * @param filename 上传文件路径
     * @param path 文件本地路径
     * @param progressCallback
     */
    public void beginupload(String filename, String path,  final ProgressCallback progressCallback) {
        //通过填写文件名形成objectname,通过这个名字指定上传和下载的文件

        String[] paths;
        String imgtype = "png";
        if(path != null && !path.equals("")){
            paths = path.split("\\.");
            imgtype = paths[paths.length - 1];
        }

        filename = filename + "/" +  String.valueOf(System.currentTimeMillis()) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000)) + "." + imgtype;

        final String objectname = filename;
        if (objectname == null || objectname.equals("")) {

            return;
        }
        //下面3个参数依次为bucket名，Object名，上传文件路径
        PutObjectRequest put = new PutObjectRequest(bucketName, objectname, path);


        if (path == null || path.equals("")) {

            //ToastUtils.showShort("请选择图片....");
            return;
        }

        //ToastUtils.showShort("正在上传中....");
        // 异步上传，可以设置进度回调


        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                double progress = currentSize * 1.0 / totalSize * 100.f;

                if (progressCallback != null) {
                    if(progress == 100.0){
                        String url = oss.presignPublicObjectURL(bucketName, objectname);
                        String resulturl = url.replace("http", "https");
                        progressCallback.onProgressCallback(progress, resulturl);
                    }else{
                        progressCallback.onProgressCallback(progress, "");
                    }
                }
            }
        });
        @SuppressWarnings("rawtypes")
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常

                if (clientExcepion != null) {
                    // 本地异常如网络异常等

                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
            }
        });
        //task.cancel(); // 可以取消任务
        //task.waitUntilFinished(); // 可以等待直到任务完成
    }



    public interface ProgressCallback {
        void onProgressCallback(double progress, String url);
    }

}
